/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * FsportDialog.java
 *
 * Created on 23.2.2010, 16:22:59
 */

package jmenu.gui;

import java.awt.print.PageFormat;
import java.awt.print.PrinterException;
import java.awt.print.PrinterJob;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.math.BigDecimal;
import java.nio.charset.Charset;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
import jmenu.main.Config;
import jmenu.main.JComponentVista;

/**
 *
 * @author Boner
 */
public class HTMLDialog extends javax.swing.JDialog {

    private MenuPanel menuPanel;
    private long MyDate;
    private String content;
    private JComponentVista vista;

    /** Creates new form FsportDialog */
    public HTMLDialog(java.awt.Frame parent, boolean modal) {
        super(parent, modal);
        initComponents();
	this.MyDate = 0;
	this.content = new String("");
    }

    public void setMenuPanel(MenuPanel mp)
    {
        this.menuPanel = mp;
	this.loadData();
    }

    private void loadData()
    {
        this.MenuLabel.setText("");
        this.content = "";

	this.content += "<body>\n";

	String [][][] data= this.menuPanel.getExportData();

	Date date = new Date();
	date.setTime(date.getTime() + this.MyDate);
        System.out.println(date.getTime());

	DateFormat dateFormat = new SimpleDateFormat("EEE, dd.MM.yyyy");

        this.content += "<br>\n";
	this.content += "<b>Den:</b> " + dateFormat.format(date)+"<br>\n";
        this.content += "<br>\n";

	double E = 0;
	double B = 0;
	double S = 0;
	double T = 0;
	double Ch = 0;

	for (int i = 0; i < 7; i++)
	{

	    if (this.EmptyMeal(data[i]))
		continue;

	    this.content += "Čas: " + data[i][0][4] + "<br>\n";

            this.content += "<ul>\n";

	    for (int j = 0; j < 5; j++)
	    {
		if (Integer.valueOf(data[i][j][0]) != 0)// && (Integer.valueOf(data[i][j][3]) != 0))
		{
		    this.content += "<li>" + data[i][j][1] + " " + data[i][j][3] + ((data[i][j][3].equals("l"))?"ml":"g" + "</li>\n");
		}
	    }

            this.content += "</ul>\n";


	    this.content += "<b>Součet:</b> " + this.getRoundedValue(Double.valueOf(data[i][5][0])) +" KJ, " + this.getRoundedValue(Double.valueOf(data[i][5][1])) + "g B, " + this.getRoundedValue(Double.valueOf(data[i][5][2])) + "g S, " + this.getRoundedValue(Double.valueOf(data[i][5][3])) + "g T, " + this.getRoundedValue(Double.valueOf(data[i][5][4])) + "mg Ch" + "<br>\n";
            this.content += "<br>\n";

	    E += Double.valueOf(data[i][5][0]);
	    B += Double.valueOf(data[i][5][1]);
	    S += Double.valueOf(data[i][5][2]);
	    T += Double.valueOf(data[i][5][3]);
	    Ch += Double.valueOf(data[i][5][4]);
	}

	this.content += "<br>\n";
	this.content += "<b>Celkem:</b> " + this.getRoundedValue(E) +" KJ, " + this.getRoundedValue(B) + "g B, " + this.getRoundedValue(S) + "g S, " + this.getRoundedValue(T) + "g T, " + this.getRoundedValue(Ch) + "mg Ch" + "\n";
        this.content += "</body>\n";
	this.content += "</html>\n";

	this.MenuLabel.setText("<html>\n" + this.content);
        this.MenuLabel.revalidate();

	vista = new JComponentVista(this.MenuLabel, new PageFormat());
	//vista.scaleToFit(true);

    }

    private void saveMenu()
    {
        JFileChooser chooser = new JFileChooser();
        chooser.setDialogType(JFileChooser.SAVE_DIALOG);
        chooser.setDialogTitle("Uložit jídelníček");
        chooser.setApproveButtonText("Uložit");
        chooser.addChoosableFileFilter(new JMenuFilterHTML());
        chooser.setMultiSelectionEnabled(false);

        int option = chooser.showDialog(Config.getMainFrame(), null);

        if (option == JFileChooser.APPROVE_OPTION)
        {
            String name = chooser.getSelectedFile().getName();

            if (!name.endsWith(".html"))
            {
                name = chooser.getSelectedFile().getAbsolutePath().concat(".html");
                chooser.setSelectedFile(new File(name));
            }

            if (!this.saveToFile(chooser.getSelectedFile()))
                JOptionPane.showMessageDialog(Config.getMainFrame(), "Nelze uložit jídelníček do HTML souboru!");
        }
    }

    private boolean saveToFile(File file)
    {
        try
        {
            if (!file.createNewFile())
                if (!file.canWrite())
                {
                    JOptionPane.showMessageDialog(Config.getMainFrame(), "Nelze zapisovat do souboru!");
                    return false;
                }

            String head = "";

            head += "<head>\n";
            head += "<title>Jdelníček - generátor jídelníčků</title>\n";
            head += "<meta http-equiv=\"Content-Type\" content=\"text/html; charset=" + Charset.defaultCharset().name() + "\">";
            head += "<meta name=\"description\" content=\"Jdelníček- generátor jídelníčků\" />\n";
            head += "</head>\n";

            String html = "<html>\n" + head + this.content;

            FileOutputStream f = new FileOutputStream(file);
            f.write(html.getBytes(Charset.defaultCharset()));
            f.flush();
            f.close();

            return true;
        }
        catch (IOException ex)
        {
            JOptionPane.showMessageDialog(Config.getMainFrame(), "Chyba při zápisu do souboru: "+ ex.getMessage() );
            return false;
        }
    }
    
    private boolean EmptyMeal( String [][] data )
    {
	for (int j = 0; j < 5; j++)
	{
	    if (Integer.valueOf(data[j][0]) != 0 && (Integer.valueOf(data[j][3]) != 0))
	    {
	        return false;
	    }
	}
	return true;
    }

    private String getRoundedValue(double value)
    {
        int decimalPlace = 2;
        BigDecimal bd = new BigDecimal( Double.toString(value) );
        bd = bd.setScale( decimalPlace, BigDecimal.ROUND_HALF_UP );
        return bd.toString();
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        DateMinusButton = new javax.swing.JButton();
        DatePlusButton = new javax.swing.JButton();
        jLabel1 = new javax.swing.JLabel();
        CloseButton = new javax.swing.JButton();
        SaveButton = new javax.swing.JButton();
        PrintButton = new javax.swing.JButton();
        jScrollPane1 = new javax.swing.JScrollPane();
        MenuLabel = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("Export pro F-sport");
        setMinimumSize(new java.awt.Dimension(516, 340));
        setResizable(false);

        DateMinusButton.setText("-");
        DateMinusButton.setMaximumSize(new java.awt.Dimension(23, 23));
        DateMinusButton.setMinimumSize(new java.awt.Dimension(23, 23));
        DateMinusButton.setName("DateMinusButton"); // NOI18N
        DateMinusButton.setPreferredSize(new java.awt.Dimension(40, 15));
        DateMinusButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                DateMinusButtonActionPerformed(evt);
            }
        });

        DatePlusButton.setText("+");
        DatePlusButton.setMaximumSize(new java.awt.Dimension(23, 23));
        DatePlusButton.setMinimumSize(new java.awt.Dimension(23, 23));
        DatePlusButton.setName("DatePlusButton"); // NOI18N
        DatePlusButton.setPreferredSize(new java.awt.Dimension(40, 15));
        DatePlusButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                DatePlusButtonActionPerformed(evt);
            }
        });

        jLabel1.setText("Datum:");
        jLabel1.setName("jLabel1"); // NOI18N

        CloseButton.setText("Zavřít");
        CloseButton.setName("CloseButton"); // NOI18N
        CloseButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                CloseButtonActionPerformed(evt);
            }
        });

        SaveButton.setText("Uložit");
        SaveButton.setToolTipText("Kopírovat do schránky");
        SaveButton.setMaximumSize(new java.awt.Dimension(40, 15));
        SaveButton.setMinimumSize(new java.awt.Dimension(40, 15));
        SaveButton.setName("SaveButton"); // NOI18N
        SaveButton.setPreferredSize(new java.awt.Dimension(40, 15));
        SaveButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                SaveButtonActionPerformed(evt);
            }
        });

        PrintButton.setText("Tisk");
        PrintButton.setToolTipText("Kopírovat do schránky");
        PrintButton.setEnabled(false);
        PrintButton.setMaximumSize(new java.awt.Dimension(40, 15));
        PrintButton.setMinimumSize(new java.awt.Dimension(40, 15));
        PrintButton.setName("PrintButton"); // NOI18N
        PrintButton.setPreferredSize(new java.awt.Dimension(40, 15));
        PrintButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                PrintButtonActionPerformed(evt);
            }
        });

        jScrollPane1.setName("jScrollPane1"); // NOI18N

        MenuLabel.setBackground(new java.awt.Color(255, 255, 255));
        MenuLabel.setHorizontalAlignment(javax.swing.SwingConstants.LEFT);
        MenuLabel.setVerticalAlignment(javax.swing.SwingConstants.TOP);
        MenuLabel.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        MenuLabel.setName("MenuLabel"); // NOI18N
        jScrollPane1.setViewportView(MenuLabel);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 496, Short.MAX_VALUE)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jLabel1)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(DateMinusButton, javax.swing.GroupLayout.PREFERRED_SIZE, 36, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(DatePlusButton, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 251, Short.MAX_VALUE)
                        .addComponent(PrintButton, javax.swing.GroupLayout.PREFERRED_SIZE, 59, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(SaveButton, javax.swing.GroupLayout.PREFERRED_SIZE, 59, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addComponent(CloseButton, javax.swing.GroupLayout.Alignment.TRAILING))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1)
                    .addComponent(DateMinusButton, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(DatePlusButton, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(SaveButton, javax.swing.GroupLayout.PREFERRED_SIZE, 15, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(PrintButton, javax.swing.GroupLayout.PREFERRED_SIZE, 15, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 499, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(CloseButton)
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void CloseButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_CloseButtonActionPerformed
	this.dispose();
    }//GEN-LAST:event_CloseButtonActionPerformed

    private void DatePlusButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_DatePlusButtonActionPerformed
	this.MyDate += 86400000;
	this.loadData();
    }//GEN-LAST:event_DatePlusButtonActionPerformed

    private void DateMinusButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_DateMinusButtonActionPerformed
	this.MyDate -= 86400000;
	this.loadData();
    }//GEN-LAST:event_DateMinusButtonActionPerformed

    private void SaveButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_SaveButtonActionPerformed
        this.saveMenu();
    }//GEN-LAST:event_SaveButtonActionPerformed

    private void PrintButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_PrintButtonActionPerformed

        vista = new JComponentVista(this.MenuLabel, new PageFormat());
        //vista.scaleToFit(true);

        PrinterJob pj = PrinterJob.getPrinterJob();
                pj.setPageable(vista);
                try
		{
                    if (pj.printDialog())
		    {
                        pj.print();
                    }
                }
		catch (PrinterException e)
		{
                    JOptionPane.showMessageDialog(Config.getMainFrame(), "Tisk se nezdařil: " + e.getMessage());
                }
    }//GEN-LAST:event_PrintButtonActionPerformed

private class JMenuFilterHTML extends javax.swing.filechooser.FileFilter
{
    public boolean accept(File file)
    {
        String filename = file.getName();
        return filename.endsWith(".html");
    }

    public String getDescription()
    {
        return "Soubory HTML (*.html)";
    }
}


    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton CloseButton;
    private javax.swing.JButton DateMinusButton;
    private javax.swing.JButton DatePlusButton;
    private javax.swing.JLabel MenuLabel;
    private javax.swing.JButton PrintButton;
    private javax.swing.JButton SaveButton;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JScrollPane jScrollPane1;
    // End of variables declaration//GEN-END:variables

}
